﻿using EventBus.RabbitMQ;
using EventBus.RabbitMQ.Events;
using Microsoft.Extensions.Hosting;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace Demo
{
    public class TestService : BackgroundService
    {
        private readonly IConsumerRegister _consumerRegister;
        private readonly IQueueBus _queueBus;

        public TestService(IConsumerRegister consumerRegister, IQueueBus queueBus)
        {
            _consumerRegister = consumerRegister;
            _queueBus = queueBus;
        }

        public override Task StartAsync(CancellationToken cancellationToken)
        {
            _consumerRegister.Start();
            return base.StartAsync(cancellationToken);
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            await Task.CompletedTask;
            while (!stoppingToken.IsCancellationRequested)
            {
                var now = DateTime.Now;
                _queueBus.Send(new LoginQueueEvent
                {
                    EventData = new LoginEvent
                    {
                        UserId = now.Second,
                        Success = (now.Second % 2) > 0
                    }
                });

                await Task.Delay(1000, stoppingToken);
            }
        }
    }
}
